/*
 * @Author: zhangwei 1405298045@qq.com
 * @Date: 2022-03-10 17:04:24
 * @LastEditTime: 2022-08-25 13:40:17
 * @LastEditors: zhangwei 1405298045@qq.com
 * @Description:
 * @FilePath: /ll-fe-mp-dyfx/src/utils/modules/login.js
 *
 */
import Store from '@/store';
import { getDyAuth } from '@/api/third';
import { getLocal } from '@/utils';
import srorageKey from '@/utils/srorage/key';
/**
 * 校验用户是否登录
 */
export const isCheckLogin = () => {
	const token = Store.getters['getToken'];
	const userInfo = Store.getters['userInfo'];
	console.log(userInfo, token);
	const url = '/authorizePage/';
	if (!token || !Object.keys(userInfo).length) {
		/* eslint-disable */
		uni.navigateTo({
			// #ifndef MP-WEIXIN
			url: `/setupPage/Login`,
			// #endif

			// #ifdef MP-WEIXIN
			url: `${url}WechatAuthorize`
			// #endif
			/* eslint enable */
		});
		return;
	}

	// #ifdef MP-WEIXIN
	if (!userInfo.userId) {
		uni.navigateTo({
			url: `${url}PhoneAuthorize`
		});

		return;
	}
	// #endif

	return true;
};

/**
 * 校验用户推广平台是否填写
 */
export const isMarketingPlatform = () => {
	if (!isCheckLogin()) {
		return;
	}

	const url = '/authorizePage/';
	const { channelCount } = Store.getters['userInfo'];

	if (!channelCount) {
		uni.navigateTo({
			url: `/thirdManage/dyAccount`
		});
		return;
	}

	return true;
};

/**
 * 统一授权登录
 * @param {*} params
 */
export const loginOut = (params = {}) => {
	const { userId, channelCount, ...otherParams } = params;

	Store.commit('changeUserInfo', {
		userId,
		channelCount,
		...otherParams
	});

	// #ifdef MP-WEIXIN
	if (!userId) {
		const url = `/authorizePage/PhoneAuthorize`;

		uni.redirectTo({
			url
		});

		return;
	}
	// #endif

	/**
	 *  渠道信息填写 （素材功能上线后， 不强制用户进行🙏🏻信息填写）
	 * 	if (!channelCount) {
	 * 		const url = `/authorizePage/TikTokGuide`;
	 *
	 * 		uni.redirectTo({
	 * 			url
	 * 		});
	 *
	 * 		return;
	 * 	}
	 */
	/* eslint-disable */
	const routes = getCurrentPages();
	if (routes?.length === 1) {
		uni.switchTab({
			url: '/pages/tabBar/Index'
		})
		return;
	}

	uni.navigateBack();
};


// 获取二维码图片
export const getDyAuthCode = () => {
	const userInfo = getLocal(srorageKey.userInfo) || {};
	if(Object.keys(userInfo).length &&userInfo.userId){
		return new Promise((resolve,reject)=>{
			getDyAuth({userId:userInfo.userId}).then((res = {})=>{
				console.log(res)
				const { data = '',code=0 } = res
				if(code===200){
					Store.commit('changeDyCodeImage',data)
					resolve(data)
				}else{
					uni.showToast({
						title:'二维码获取失败',
						icon:'none'
					})
				}
				
			})
			.catch((err)=>{
				reject(err)
			})
		})
	}else{
		return new Promise((resolve,reject)=>{
			resolve(true)
		})
	}
}